﻿using AutoMapper;
using IMES.Common.Domain.DariusModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;

namespace Darius.API.Application.Commands
{
    public class UsersSelectHandler : IRequestHandler<UsersSelectCommand, Result>
    {
        private readonly IMapper mapper;
        private readonly IBaseRepositorys<Users> usersRep;
        private readonly IBaseRepositorys<Roles> rolesRep;

        public UsersSelectHandler(IMapper mapper, IBaseRepositorys<Users> usersRep, IBaseRepositorys<Roles> rolesRep)
        {
            this.mapper = mapper;
            this.usersRep = usersRep;
            this.rolesRep = rolesRep;
        }

        /// <summary>
        /// 用户显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(UsersSelectCommand request, CancellationToken cancellationToken)
        {
            var quest = new Result() { Code = (int)CodeEnum.success };
            var list = (from a in usersRep.GetAll()
                        join b in rolesRep.GetAll() on a.RoleId equals b.RoleId
                        select new UsersRoleDto()
                        {
                            UsersId = a.UsersId,
                            UserAccount = a.UserAccount,
                            UsersName = a.UsersName,
                            Gender = a.Gender,
                            UsersImage = a.UsersImage,
                            RoleId = b.RoleId,
                            RoleName = b.RoleName,
                            UsersDate = a.UsersDate,
                            CreateName = a.CreateName
                        });

            if (!string.IsNullOrEmpty(request.UserAccount))
            {
                list = list.Where(a => a.UserAccount.Contains(request.UserAccount));
            }

            quest.Code = (int)CodeEnum.success;
            quest.Data = list;
            return quest;
        }
    }
}
